import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchServer {
    private DatagramSocket socket = null;

    //服务器需要绑定的窗口
    public UdpEchServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            DatagramPacket requestPacker = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacker);
            String request = new String(requestPacker.getData(), 0, requestPacker.getLength());
            //2.根据请求，计算出响应
            String response = process(request);
            //3.把响应写回客户端，此时需要告知网卡，要发的内容是什么，发给谁。
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacker.getSocketAddress());
            socket.send(requestPacker);
            System.out.printf("[%s:%d] rep:%s,resp:%s\n", requestPacker.getAddress().toString(), requestPacker.getPort(), request, response);


        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchServer server = new UdpEchServer(90);
        server.start();
    }

}